package com.tanhua.app.intercept;

import cn.hutool.http.HttpStatus;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenIntercept extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("Authorization");

        //2.校验token
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken){
            //校验失败(HttpStatus:cn.hutool.http)
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            //失败后就拦截
            return false;
        }

        //3.解析token
        Claims claims = JwtUtils.getClaims(token);
        long id = Long.parseLong(claims.get("id").toString());
        String mobile = claims.get("phone").toString();

        //4.存储解析的用户数据
        User user = new User();
        user.setId(id);
        user.setMobile(mobile);
        UserHolder.set(user);

        //5.返回true,放行
        return true;


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
